package com.xuecheng.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.onlinelearn.base.exception.OnlineLearnException;
import com.onlinelearn.base.model.PageParams;
import com.onlinelearn.base.model.PageResult;
import com.onlinelearn.base.model.RestResponse;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.model.dto.UploadFileResultDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.service.MediaFileService;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.asn1.pkcs.MacData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Mr.M
 * @version 1.0
 * @description TODO
 * @date 2022/9/10 8:58
 */
@Service
@Slf4j
public class MediaFileServiceImpl implements MediaFileService {

    @Autowired
    MediaFileService proxyMediaFileService;
    @Autowired
    MediaFilesMapper mediaFilesMapper;

    @Autowired
    MinioClient minioClient;

    @Autowired
    MediaProcessMapper mediaProcessMapper;

    @Value("${minio.bucket.files}")
    private String mediafiles;

    @Value("${minio.bucket.videofiles}")
    private String videofiles;



    @Override
    public PageResult<MediaFiles> queryMediaFiels(Long companyId, PageParams pageParams, QueryMediaParamsDto queryMediaParamsDto) {

        //构建查询条件对象
        LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(MediaFiles::getFilename,queryMediaParamsDto.getFilename());
        //分页对象
        Page<MediaFiles> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<MediaFiles> pageResult = mediaFilesMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<MediaFiles> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<MediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return mediaListResult;

    }

//    根据扩展名拿文件类型
    private String getMimeType(String extension){
        ContentInfo extensionMatch = null;
        if(extension != null){
            //        拿扩展名,用类型
            extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        }
//        拿不到就用字节流
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;//通用mimeType，字节流
        if(extensionMatch != null){
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }

//    文件上传
    public boolean addMediaFilesToMinIO(String localFilePath,String mimeType,String bucket, String objectName){
        try {
            UploadObjectArgs testbucket = UploadObjectArgs.builder()
                    .bucket(bucket)
                    .filename(localFilePath)
                    .object(objectName)
                    .contentType(mimeType)
                    .build();
            minioClient.uploadObject(testbucket);
            return true;
        } catch (Exception e) {
            log.error("上传文件出错,bucket:{},objectName:{},错误信息:{}",bucket,objectName,e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public MediaFiles getFileById(String mediaId) {
        return mediaFilesMapper.selectById(mediaId);
    }

    //    获取文件的md5值
    private String getMd5(File file){
        String md5Hex = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            md5Hex = DigestUtils.md5Hex(fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return md5Hex;
    }
    //获取文件默认存储目录路径 年/月/日
    private String getDefaultFolderPath() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String folder = sdf.format(new Date()).replace("-", "/")+"/";
        return folder;
    }

    /**
     * 上传文件(这里做的是上传图片,没有分块上传)
     * @param companyId           机构id
     * @param uploadFileParamsDto 上传文件信息
     * @param localFilePath       文件磁盘路径
     * @return
     */
    public UploadFileResultDto uploadFile(Long companyId, UploadFileParamsDto uploadFileParamsDto, String localFilePath,String objectName) {
        String filename = uploadFileParamsDto.getFilename();
        String extension = filename.substring(filename.lastIndexOf("."));
        String mimeType = getMimeType(extension);
        String defaultFolderPath = getDefaultFolderPath();
        String md5 = getMd5(new File(localFilePath));
        if(StringUtils.isEmpty(objectName)){
            objectName = defaultFolderPath + md5 + extension;
        }
//        上传minio
        boolean bool = addMediaFilesToMinIO(localFilePath, mimeType, mediafiles, objectName);
        UploadFileResultDto uploadFileResultDto;
        if(bool){
            MediaFiles mediaFiles = proxyMediaFileService.addMediaFilesToDb(companyId, md5, uploadFileParamsDto, mediafiles, objectName);
            if(mediaFiles != null){
                uploadFileResultDto = new UploadFileResultDto();
                BeanUtils.copyProperties(mediaFiles,uploadFileResultDto);
                return uploadFileResultDto;
            }else {
                OnlineLearnException.cast("文件上传插库失败!");
            }
        }else{
            OnlineLearnException.cast("文件上传插入数据库失败!");
        }

        return null;
    }

    /**
     *
     * @param companyId 机构id
     * @param fileMd5   md5值
     * @param uploadFileParamsDto   上传参数
     * @param bucket    桶
     * @param objectName    minio的objectName
     * @return
     * 为什么在这里加事务注解  因为文件上传接口需要上传minio,可能占用时间比较长,因为需要缩小事务的范围到数据库插入
     * 为什么直接调用方法事务无法生效    因为spring中事务需要
     * 1.代理对象执行2.有Transactional注解的方法才能生效,因此需要注入本身来调用方法3.抛出异常4.必须是公有,或者是默认,否则相当于没加
     */
    @Transactional
    public MediaFiles addMediaFilesToDb(Long companyId,String fileMd5,UploadFileParamsDto uploadFileParamsDto,String bucket,String objectName){
        MediaFiles mediaFiles = new MediaFiles();
        mediaFiles.setId(fileMd5);
        mediaFiles = mediaFilesMapper.selectById(mediaFiles);
        if(mediaFiles == null){
            mediaFiles = new MediaFiles();
            //            插数据库
            BeanUtils.copyProperties(uploadFileParamsDto,mediaFiles);
//            设置id
            mediaFiles.setId(fileMd5);
//            设置机构id
            mediaFiles.setCompanyId(companyId);
//            设置文件id
            mediaFiles.setFileId(fileMd5);
//            桶
            mediaFiles.setBucket(bucket);
//            文件存储路径
            mediaFiles.setFilePath(objectName);
//            url
            mediaFiles.setUrl("/"+bucket+"/"+objectName);
//            上传时间
            mediaFiles.setCreateDate(LocalDateTime.now());
//            状态
            mediaFiles.setStatus("1");
//            审核状态
            mediaFiles.setAuditStatus("002003");
            int insert = mediaFilesMapper.insert(mediaFiles);
            if(insert <= 0){
                log.error("文件上传数据插入失败,bucket{},objectName{}",bucket,objectName);
                return null;
            }
//            如果是指定类型的格式视频,需要转码成mp4
            //添加到待处理任务表
            addWaitingTask(mediaFiles);
            log.debug("保存文件信息到数据库成功,{}", mediaFiles.toString());
            return mediaFiles;
        }else{
            return mediaFiles;
        }
    }

    /**
     * 添加任务到任务表中,指定类型文件才插入
     * @param mediaFiles
     */
    private void addWaitingTask(MediaFiles mediaFiles){

        MediaProcess mediaProcess = new MediaProcess();
        mediaProcess.setFileId(mediaFiles.getFileId());
        LambdaQueryWrapper<MediaProcess> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MediaProcess::getFileId,mediaFiles.getFileId());
        MediaProcess tt = mediaProcessMapper.selectOne(lambdaQueryWrapper);
        if(tt != null){
            log.error("重复插入!FileId:{}",mediaFiles.getFileId());
            return;
        }
        String filename = mediaFiles.getFilename();
        String substring = filename.substring(filename.lastIndexOf("."));
        String mimeType = getMimeType(substring);
        if(mimeType.equals("video/x-msvideo")){
            BeanUtils.copyProperties(mediaFiles,mediaProcess);
            mediaProcess.setStatus("1");
            mediaProcess.setCreateDate(LocalDateTime.now());
            mediaProcess.setUrl("");
            mediaProcess.setFailCount(0);
            int insert = mediaProcessMapper.insert(mediaProcess);
            if(insert < 1){
                log.error("插入任务表失败!FileId:{}",mediaFiles.getFileId());
            }
        }
    }

    @Override
    public RestResponse<Boolean> checkfile(String fileMd5) {
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
//        如果数据库中有数据,就拿出他的minio配置
        if(mediaFiles != null){
//            桶
            String bucket = mediaFiles.getBucket();
//            minio中的存储目录
            String filePath = mediaFiles.getFilePath();
            InputStream inputStream = null;
            try {
                inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(filePath).build());
                //            文件已经存在
                if(inputStream != null){
                    return RestResponse.success(true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return RestResponse.success(false);
    }

    @Override
    public RestResponse<Boolean> checkchunk(String fileMd5, int chunk) {
//        分块文件目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
//        分块文件的路径
        String chunkFilePath = chunkFileFolderPath + chunk;

        InputStream inputStream = null;

        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(videofiles).object(chunkFilePath).build());
            if(inputStream != null){
                //分块已存在
                return RestResponse.success(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //分块未存在
        return RestResponse.success(false);
    }

    @Override
    public RestResponse uploadChunk(String fileMd5,int chunk,String localChunkFilePath) {
//        分块目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
//        分块路径
        String chunkFilePath = chunkFileFolderPath + chunk;
        String mimeType = getMimeType("");
        boolean b = addMediaFilesToMinIO(localChunkFilePath, mimeType, videofiles, chunkFilePath);
        if(!b){
            log.debug("视频文件上传失败,bucket:{},md5:{},chunkFilePath{}",videofiles,fileMd5,chunkFilePath);
            return RestResponse.validfail(false,"上传失败!");
        }
        return RestResponse.success(true);
    }

    @Override
    public RestResponse mergechunks(Long companyId, String fileMd5, int chunkTotal, UploadFileParamsDto uploadFileParamsDto) {
//        用minio的api合并分块
//        获取分块的目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        List<ComposeSource> sources = Stream.iterate(0, i -> ++i).limit(chunkTotal).map(j -> ComposeSource.builder().bucket(videofiles).object(chunkFileFolderPath+j).build()).collect(Collectors.toList());
//        获得合并后文件的路径
        String filename = uploadFileParamsDto.getFilename();
        String extName = filename.substring(filename.lastIndexOf("."));
//        这个文件名称应该会少一个点
        String objectName = getFilePathByMd5(fileMd5, extName);
        try {
            ComposeObjectArgs testbucket = ComposeObjectArgs.builder()
                    .bucket(videofiles)
                    .object(objectName)
                    .sources(sources)
                    .build();
            minioClient.composeObject(testbucket);
            log.debug("和并文化分块成功!");
        } catch (Exception e) {
            log.error("合并文件分块失败!fileMd5{},异常{}",fileMd5,e.getMessage(),e);
            e.printStackTrace();
        }
//        校验分块是否合并成功
        File file = downloadFileFromMinIO(videofiles, objectName);

        if(file == null){
            log.debug("下载合并后文件失败,objectName:{}",objectName);
            RestResponse.validfail(false,"合并文件失败!");
        }
        try(InputStream inputStream = new FileInputStream(file)) {
            String mergerMd5 = DigestUtils.md5Hex(inputStream);
            //比较md5值，不一致则说明文件不完整
            if(!fileMd5.equals(mergerMd5)){
                return RestResponse.validfail(false, "文件合并校验失败，最终上传失败。");
            }
            //文件大小
            uploadFileParamsDto.setFileSize(file.length());
        } catch (Exception e) {
            e.printStackTrace();
        }

//        合并成功后入库
        proxyMediaFileService.addMediaFilesToDb(companyId,fileMd5,uploadFileParamsDto,videofiles,objectName);
//        清理分块
        clearChunkFiles(chunkFileFolderPath,chunkTotal);
        return RestResponse.success();
    }
//    获得文件的的ObjectName
    private String getFilePathByMd5(String fileMd5,String fileExt){
        return   fileMd5.substring(0,1) + "/" + fileMd5.substring(1,2) + "/" + fileMd5 + "/" +fileMd5 +fileExt;
    }

    //得到分块文件的目录     分块文件目录是按md5的前2位分为2级目录,目的是防止数据量太大,浪费太多的时间io
    private String getChunkFileFolderPath(String fileMd5) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + "chunk" + "/";
    }
    /**
     * 从minio下载文件
     * @param bucket 桶
     * @param objectName 对象名称
     * @return 下载后的文件
     */
    public File downloadFileFromMinIO(String bucket,String objectName){
        //临时文件
        File minioFile = null;
        FileOutputStream outputStream = null;
        try{
            InputStream stream = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .build());
            //创建临时文件
            minioFile=File.createTempFile("minio", ".merge");
            outputStream = new FileOutputStream(minioFile);
            IOUtils.copy(stream,outputStream);
            return minioFile;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 清除分块文件
     * @param chunkFileFolderPath 分块文件路径
     * @param chunkTotal 分块文件总数
     */
    private void clearChunkFiles(String chunkFileFolderPath,int chunkTotal) {

        try {
            List<DeleteObject> deleteObjects = Stream.iterate(0, i -> ++i)
                    .limit(chunkTotal)
                    .map(i -> new DeleteObject(chunkFileFolderPath.concat(Integer.toString(i))))
                    .collect(Collectors.toList());

            RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder().bucket("video").objects(deleteObjects).build();
            Iterable<Result<DeleteError>> results = minioClient.removeObjects(removeObjectsArgs);
            results.forEach(r -> {
                DeleteError deleteError = null;
                try {
                    deleteError = r.get();
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("清楚分块文件失败,objectname:{}", deleteError.objectName(), e);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("清楚分块文件失败,chunkFileFolderPath:{}", chunkFileFolderPath, e);
        }
    }
}
